package com.abocode.aichat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class TcpClient {

    public Bootstrap bootstrap;
    public Channel channel;

    public TcpClient(String host, int port) {
        this.bootstrap = initBootstrap();
        this.channel = initChannel(host, port);
        if (channel == null) {
            throw new NullPointerException("channel is null");
        }
    }

    /**
     * 初始化Bootstrap
     *
     * @return
     */
    public final Bootstrap initBootstrap() {
        EventLoopGroup group = new NioEventLoopGroup(10);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast("handler", new TcpClientHandler());
            }
        });
        b.option(ChannelOption.SO_KEEPALIVE, true);
        return b;
    }

    public final Channel initChannel(String host, int port) {
        Channel channel = null;
        try {
            channel = bootstrap.connect(host, port).sync().channel();
            System.out.println("链接成功");
        } catch (Exception e) {
            return null;
        }
        return channel;
    }

    public void sendMsg(String msg) throws Exception {
        if (channel != null) {
            channel.writeAndFlush(msg).sync();
        } else {
            System.out.println("消息发送失败,连接尚未建立!");
        }
    }

    public void close() throws Exception {
        if (channel != null) {
            channel.close();
        } else {
            System.out.println("close失败,连接尚未建立!");
        }
    }
}

